import React, { useState } from "react";
import COS, { CosError } from "cos-js-sdk-v5";
import { Button, Modal, Form, Input, Radio, Upload, message, Spin } from "antd";
import { PlusOutlined, UploadOutlined } from "@ant-design/icons";

const { TextArea } = Input;
const layout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 16 },
};
const tailLayout = {
  wrapperCol: { offset: 4, span: 16 },
};
const validateMessages = {
  // eslint-disable-next-line no-template-curly-in-string
  required: "${label} 是必填的！",
};
const Bucket = "sss-1306551685"; /* 存储桶 */
const Region = "ap-guangzhou";
const cos = new COS({
  SecretId: "AKIDg9NL2SdXAXeV6QTGmDTUIsDJ9j5C3f17",
  SecretKey: "rSmriJflcDYeW9WdT3MPCk12mHXYKsBE",
});

interface IInfo {
  onAddInfo: Function;
  isModalVisible: boolean;
  onCancel: Function;
  onReset: Function;
}

const AddInfo: React.FC<IInfo> = ({
  onAddInfo,
  isModalVisible,
  onCancel,
  onReset,
}): React.ReactElement => {
  const [isSpinning, setisSpinning] = useState(false);
  const [isTip, setTip] = useState("正在数据录入.....");

  const [form] = Form.useForm();

  let arr: any[] = [];

  function uploadChange(fileData: any, url: string) {
    const files = {
      Body: "",
      Bucket: "",
      Key: "",
      Region: "",
    };
    files.Body = fileData;
    files.Bucket = Bucket;
    // files.Bucket = Bucket
    files.Key = url + "/" + fileData.name;
    files.Region = Region;
    let arrList = [];
    arrList.push(files);

    cos.uploadFiles(
      {
        files: arrList,
        SliceSize: 1024 * 1024 * 10,
        /* 设置大于10MB采用分块上传 */
        onProgress: function (info) { },
        onFileFinish: function (err: CosError, options: any) {
          arr.push(options);
        },
      },
      (err, data) => {
        if (err) {
          console.log("上传失败", err);
          return;
        }
      }
    );
  }

  const onFinish = (values: any) => {
    setisSpinning(true);
    values.date = new Date();
    values.MediaType = values.MediaType === "a" ? "视频" : "图片";
    let str = "";
    for (var i = 0; i < values.upload.length; i++) {
      let url = "Videonumber";
      uploadChange(values.upload[i].originFileObj, url);
      console.log(values.upload[i].name);
      str += values.upload[i].name + " ";
      values.Media = str;
    }

    let timer: any = setInterval(() => {
      if (arr.length === values.upload.length) {
        setTip("请稍后...");
        clearInterval(timer);
        setisSpinning(false);
        onAddInfo(values, form);

      }
    }, 1000);
  };

  const onResets = () => {
    onReset(form);
  };

  const onSubmit = async () => {
    const formValues = form.getFieldsValue();
    try {
      const values = await form.validateFields();
      console.log("Success:", values);
      onFinish(formValues);
    } catch (errorInfo) {
      message.warn("提交校验失败");
    }
  };

  const normFile = (e: any) => {
    console.log("Upload event:", e);
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };

  return (
    <div className="add_btn_info">
      <Button
        onClick={() => {
          onCancel(true);
        }}
        icon={<PlusOutlined />}
        type="ghost"
      >
        新增
      </Button>

      <Modal
        title="发布数据"
        visible={isModalVisible}
        footer={null}
        onCancel={() => {
          onCancel(false);
        }}
      >
        <Spin tip={isTip} spinning={isSpinning}>
          <Form
            {...layout}
            form={form}
            name="control-hooks"
            validateMessages={validateMessages}
            onFinish={onFinish}
          >
            <Form.Item
              name="userName"
              label="发布者"
              rules={[{ required: true }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="MediaType"
              label="数据类型"
              rules={[{ required: true, message: "Please pick an item!" }]}
            >
              <Radio.Group>
                <Radio.Button value="a">视频</Radio.Button>
                <Radio.Button value="b">图片</Radio.Button>
              </Radio.Group>
            </Form.Item>
            <Form.Item name="address" label="地址" rules={[{ required: true }]}>
              <Input />
            </Form.Item>
            <Form.Item name="message" label="内容" rules={[{ required: true }]}>
              <TextArea rows={4} />
            </Form.Item>
            <Form.Item name="type" label="数据标签">
              <Radio.Group>
                <Radio value="美妆">美妆</Radio>
                <Radio value="数码">数码</Radio>
                <Radio value="科技">科技</Radio>
                <Radio value="生活">生活</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item
              name="upload"
              label="上传数据"
              valuePropName="fileList"
              getValueFromEvent={normFile}
              rules={[{ required: true }]}
            >
              <Upload name="logo" action="#" listType="picture">
                <Button icon={<UploadOutlined />}>立即上传</Button>
              </Upload>
            </Form.Item>
            <Form.Item {...tailLayout}>
              <Button type="primary" onClick={onSubmit}>
                提交
              </Button>
              <Button htmlType="button" onClick={onResets}>
                重置
              </Button>
            </Form.Item>
          </Form>
        </Spin>
      </Modal>
    </div>
  );
};

export default AddInfo;
